package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.MemberCoupon;
import com.xinhe.web.entity.QMemberCoupon;
import com.xinhe.web.reposity.MemberCouponRepository;
import com.xinhe.web.request.MemberCouponModel;
import com.xinhe.web.session.UserSessionManager;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Service

public class MemberCouponService {
    @Autowired
    private MemberCouponRepository memberCouponRepository;
    @Autowired
    private UserSessionManager userSessionManager;
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public QueryResults<MemberCoupon> pageMemberCoupon(int pageNum, int pageSize) {
        QMemberCoupon qMemberCoupon = QMemberCoupon.memberCoupon;
        BooleanBuilder builder = new BooleanBuilder();
        //OrderSpecifier<Date> sort = qMemberCoupon.createTime.desc();
        //builder.and(qMemberCoupon.removed.eq(0));
        return queryFactory.select(
                Projections.bean(
                        MemberCoupon.class,
                        qMemberCoupon.name,
                        qMemberCoupon.couponId,
                        qMemberCoupon.expireTime,
                        qMemberCoupon.money,
                        qMemberCoupon.satisfyMoney,
                        qMemberCoupon.status,
                        qMemberCoupon.userId,
                        qMemberCoupon.id
                )
        ).from(qMemberCoupon)
                .where(builder).offset(pageNum * pageSize).limit(pageSize).fetchResults();
    }

    @Transactional
    public Result automaticUpdateExpireMemberCoupon() {
        List<MemberCoupon> list = this.memberCouponRepository.findExpire();
        if (CollectionUtils.isNotEmpty(list)) {
            list = (List<MemberCoupon>)list.stream().peek(memberCoupon -> memberCoupon.setStatus("EXPIRE")).collect(Collectors.toList());
            this.memberCouponRepository.saveAll(list);
        }
        return Result.ok();
    }

    public Result findById(Long memberCouponId) {
        return Result.ok(memberCouponRepository.findById(memberCouponId).get());
    }

    public Result delete(Long memberCouponId) {
        memberCouponRepository.deleteById(memberCouponId);
        return Result.ok();
    }

    @Transactional
    public Result saveModel(@Valid MemberCouponModel model) {
        MemberCoupon memberCoupon = new MemberCoupon();
        memberCoupon.setUserId(model.getUserId());
        memberCoupon.setName(model.getName());
        memberCoupon.setExpireTime(model.getExpireTime());
        memberCoupon.setMoney(model.getMoney());
        memberCoupon.setSatisfyMoney(model.getSatisfyMoney());
        if (memberCoupon.getExpireTime().compareTo(new Date()) <= 0) {
            memberCoupon.setStatus("EXPIRE");
        } else {
            memberCoupon.setStatus("NOT_USE");
        }
        this.memberCouponRepository.save(memberCoupon);
        return Result.ok();
    }
}
